package com.pai4j.zwiki.messagequeue.consumer.redis;

import com.pai4j.common.util.JsonUtil;
import com.pai4j.zwiki.dto.ZWikiNotificationMessage;
import com.pai4j.zwiki.messagequeue.consumer.service.ZWikiNotificationConsumeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * ZWiki队列更新Redis监听器
 * 监听队列位置更新通知
 *
 * @author pai4j
 * @since 2025-10-14
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ZWikiQueueUpdateRedisListener implements MessageListener {

    private final RedisTemplate<String, Object> redisTemplate;
    private final ZWikiNotificationConsumeService notificationConsumeService;

    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {
            String channel = (String) redisTemplate.getStringSerializer().deserialize(message.getChannel());
            String messageStr = (String) redisTemplate.getStringSerializer().deserialize(message.getBody());
            
            log.debug("收到ZWiki队列更新通知: channel={}, message={}", channel, messageStr);
            
            // 解析通知消息
            ZWikiNotificationMessage notification = JsonUtil.fromJson(messageStr, ZWikiNotificationMessage.class);
            
            if (notification == null) {
                log.warn("队列更新通知消息解析失败: {}", messageStr);
                return;
            }
            
            // 处理队列更新通知
            notificationConsumeService.handleQueueUpdateNotification(notification);
            
        } catch (Exception e) {
            log.error("处理ZWiki队列更新通知失败", e);
        }
    }
}

